<?php 
namespace WeiChatLib;

/**
* 常用函数集合
*/
class Func{
	const jsonData="json";
	const xmlData="xml";
	//默认返回的数组的键值都是小些的
	public function stringDataToaArr($data,$type=self::jsonData){
		if($type==self::jsonData){
			$resultData=json_decode($data,true);
			if(!is_array($resultData)){
				throw new \Exception("json parse error", 1);exit;
			}
		}elseif($type==self::xmlData){
			$resultData=simplexml_load_string($data,"SimpleXMLElement",LIBXML_NOCDATA);
			if(!is_object($resultData)){
				throw new \Exception("xml parse error", 1);exit;
			}
		}
		// return array_change_key_case($resultData);
		return $resultData;
	}
	/**
	 * 递归遍历数组  赋值给SimpleXmlElement
	 * @param  [type] $ele   [description]
	 * @param  [type] $key   [description]
	 * @param  [type] $value [description]
	 * @return [type]        [description]
	 */
	private function xmlRecursion($ele,$key,$value){
		if(is_array($value)){
			$ele1=$ele->addChild($key);
			foreach ($value as $key1 => $value1) {
				$this->xmlRecursion($ele1,$key1,$value1);
			}
		}else{
			//<![CDATA[     ]]>
			if(!is_numeric($value)){
				$value="<![CDATA[".$value."]]>";
			}
			$ele->addChild($key,$value);
			return;
		}
	}
	/**
	 * 将arr转化成json字符串或者是xml
	 * @return [type] [description]
	 */
	public function arrToStringData($arr,$type=self::jsonData){
		if($type==self::jsonData){
			return json_encode($arr);
		}elseif($type==self::xmlData){
			$xmlTemplete=<<<XML
			<xmlElement></xmlElement>
XML;
			$SimpleXMLElement=simplexml_load_string($xmlTemplete, 'SimpleXMLElement', LIBXML_NOCDATA);
			$this->xmlRecursion($SimpleXMLElement,"xml",$arr);
			return htmlspecialchars_decode($SimpleXMLElement->children()->asXML());
		}
	}
	/**
	 *  测试超时时间
	 * @param  [type]  $time    [记录的之前旧的时间]
	 * @param  [type]  $OutTime [超时的时间]
	 * @return boolean          [是否超时 true 是 false 否]
	 */
	function isAccessTokenTimeout($timeOld,$OutTime){
		if(($time=strstr($OutTime,"h",true))!==false){
			$timeSecend=$time*3600;
		}elseif(($time=strstr($OutTime,"m",true))!==false){
			$timeSecend=$time*60;
		}elseif(($time=strstr($OutTime,"s",true))!==false){
			$timeSecend=$time;
		}else{
			$timeSecend=$OutTime;
		}
		if(time()-$timeOld>=$timeSecend){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 检查是否是请求出错
	 * @param  [type]  $arr [返回的json转化成数组]
	 * @return boolean      [description]
	 */
	public function isWeiChatError($arr){
		if(is_array($arr)){
			return false;
		}
		$keys=array_keys($arr);
		if(in_array("errcode",$keys)&&in_array("errmsg",$keys)){
			if($arr['errcode']==0){
				return false;
			}
			throw new \Exception("WeiChat Error".$arr['errmsg'], 1);
		}
	}
	/**
	 * 加密消息
	 * @param  [type] $messge [description]
	 * @return [type]         [description]
	 */
	public function encryptMeg($messge){

	}
	/**
	 * 解密
	 * @return [type] [description]
	 */
	public function decryptionMeg(){

	}

	public function isEncrypt(){
		// $_GET['']
	}
}